import { ApiResponse, LoginFormType } from '@/types/data'
import { LoginAction, RootThunkAction, Token } from '@/types/store'
import request from '@/utils/request'
import { removeToken, setToken } from '@/utils/storage'

// 保存token的action
export const saveToken = (token: Token): LoginAction => {
  // 将 token 存入本地
  setToken(token)
  return {
    type: 'login/getToken',
    payload: token,
  }
}

// 退出action
export const logout = (): LoginAction => {
  removeToken()
  return {
    type: 'login/logout',
  }
}

// 登录action
export const login = (values: LoginFormType): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.post<ApiResponse<Token>>(
      '/authorizations',
      values
    )
    // console.log(res)

    //将token存入redux
    dispatch(saveToken(res.data.data))
  }
}

// 发送验证码action
export const getMobileCode = (mobile: string): RootThunkAction => {
  return async (dispatch) => {
    const res = await request.get(`/sms/codes/${mobile}`)
    console.log(res)
  }
}
